package com.mproject.activity;

import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.mproject.activity.project.Project_TabView;
import com.mproject.adapter.Dashboard_List_Project_Adapter;
import com.mproject.customclass.Project;
import com.mproject.network.IVLE_API_Helper;
import com.mproject.network.ProgressBarManager;

public class Dashboard_ListProject extends Activity implements OnClickListener{

	public static SharedPreferences mypref;
	private String token = "";

	public final static String project_name= "Item one";  
	public final static String project_next_meeting = "Item two";
	public final static String project_next_deadline = "Item three";
	public final static String project_id = "Item four";

	private TextView date;
	private static final String dateTemplate = "EEEE, dd MMMM yyyy";

	private TextView addProject;

	List<Project> listProjects;

	List<Map<String,?>> project_leading;
	List<Map<String,?>> project_joining;

	private ListView project_list;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dashboard_project_list); 
		date = (TextView)findViewById(R.id.dashboard_date);
		Calendar currentDate = Calendar.getInstance(Locale.getDefault());
		date.setText(DateFormat.format(dateTemplate, currentDate.getTime()));

		addProject = (TextView) findViewById(R.id.dashboard_add_project);
		addProject.setOnClickListener(this);

	}

	public void onResume() {
		super.onResume();
		addProject.setVisibility(View.INVISIBLE);
		loadingContent();
	}
	public void onPause() {
		super.onPause();
		project_list.setAdapter(null);
	}



	public void loadingContent() {
		ProgressBarManager manager=new ProgressBarManager(Dashboard_ListProject.this.getParent())
		{

			protected void onPreExecute() {

				Log.v("manager"," in pre execute");

				dialog.setMessage("Loading please wait...");
				dialog.setIndeterminate(true);

				// dialog.setTitle("Manager");
				dialog.show();
			}

			protected Boolean doInBackground(String... params) 
			{

				try {
					//fill project list of the user
					mypref=getSharedPreferences("My_Prefs",Activity.MODE_WORLD_WRITEABLE);
					token = mypref.getString("IVLE_Token", "");
					listProjects = IVLE_API_Helper.getAllProjects(token);
					return true;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return false;
				}


			}
			protected void onPostExecute(Boolean result) {
				this.getDialog().dismiss();
				if (result == false) {
					AlertDialog.Builder builder = new AlertDialog.Builder(Dashboard_ListProject.this.getParent());
					builder.setMessage("No internet connection")
					.setNegativeButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}

					});
					AlertDialog alert = builder.create();
					alert.show();
				}
				else {
					addProject.setVisibility(View.VISIBLE);
					fillProjectList();
				}
			}
		};
		manager.execute();
	}

	public Map<String,?> createItem(String name, String meeting, String deadline, String id) {  
		Map<String,String> item = new HashMap<String,String>();  
		item.put(project_name, name);  
		item.put(project_next_meeting, meeting);  
		item.put(project_next_deadline, deadline); 
		item.put(project_id, id);
		return item;  
	}

	public void fillProjectList() {

		project_list = (ListView) findViewById(R.id.dashboard_list_project);
		//testting - static value here
		project_leading = new LinkedList<Map<String,?>>();
		project_joining = new LinkedList<Map<String,?>>(); 

		for (Project project : listProjects) {
			if (project.isManager()) {
				project_leading.add(createItem(project.getTitle(), "02-05-12", "28-05-12", project.getID()));  
			}
			else {
				project_joining.add(createItem(project.getTitle(), "02-05-12", "28-05-12", project.getID()));  
			}
		}


		Dashboard_List_Project_Adapter adapter = new Dashboard_List_Project_Adapter(this);
		if (project_leading.size() > 0) {
			adapter.addSection("Projects you are leading", new SimpleAdapter(this, project_leading, R.layout.dashboard_project_list_item,  
					new String[] { project_name, project_next_meeting, project_next_deadline, project_id }, new int[] { R.id.dashboard_project_name, R.id.dashboard_project_meeting, R.id.dashboard_project_deadline, R.id.dashboard_project_id}));
		}
		if (project_joining.size() > 0) {
			adapter.addSection("Projects you are joining", new SimpleAdapter(this, project_joining, R.layout.dashboard_project_list_item,  
					new String[] { project_name, project_next_meeting, project_next_deadline, project_id }, new int[] { R.id.dashboard_project_name, R.id.dashboard_project_meeting, R.id.dashboard_project_deadline, R.id.dashboard_project_id}));
		}


		project_list.setAdapter(adapter);

		project_list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> listView, View itemView, int position, long id) {
				Intent projectIntent = new Intent (Dashboard_ListProject.this, Project_TabView.class);
				TextView proj_id = (TextView)itemView.findViewById(R.id.dashboard_project_id);
				Project prj = findProject(proj_id.getText().toString());

				//put info
				mypref=getSharedPreferences("My_Prefs",Activity.MODE_WORLD_WRITEABLE);
				SharedPreferences.Editor editor=mypref.edit();
				editor.putString("project_id",prj.getID());
				editor.putString("project_title",prj.getTitle());
				editor.putString("project_cat",prj.getCategory());
				editor.putString("project_des",prj.getDescription());
				editor.putBoolean("project_is_manager",prj.isManager());
				editor.putString("project_open",prj.getOpenDate());
				editor.putString("project_expiry",prj.getExpiryDate());
				editor.commit();

				startActivity(projectIntent);

			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == addProject) {
			Intent intent = new Intent(Dashboard_ListProject.this, AddProjectActivity.class);
			startActivity(intent);
		}

	}

	//find project inside project list
	private Project findProject(String id) {
		for (Project project : listProjects) {
			if (project.getID().equals(id)) {
				return project;
			}
		}
		return null;
	}
}
